﻿using Sustainalytics.Controversies.BusinessLogic;
using Sustainalytics.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.Accounts.BusinessLogic
{
    public class UserIpLoginManager : IUserIpLoginManager
    {
        private IPlainBl<User> _plainBlUser;
        private IPlainBl<ClientUser> _plainBlClientUser;

        private UserIpLoginManager() { }
        public UserIpLoginManager(IPlainBl<User> plainBlUser, IPlainBl<ClientUser> plainBlClientUser)
        {
            _plainBlUser = plainBlUser;
            _plainBlClientUser = plainBlClientUser;
        }

        public static IUserIpLoginManager GetInstance(IPlainBl<User> plainBlUser, IPlainBl<ClientUser> plainBlClientUser)
        {
            return new UserIpLoginManager
            {
                _plainBlUser = plainBlUser,
                _plainBlClientUser = plainBlClientUser
            };
        }

        public User GetFakeUserIp(Guid accountId)
        {
            return (_plainBlUser.ReadAllWhere(a => a.AccountId == accountId && a.IsFakeIpUser) ?? new List<User>()).FirstOrDefault(a => a.AccountId == accountId && a.IsFakeIpUser);
        }

        public User GetFakeUserIp(Guid id, string accountName, string firsIpAdress)
        {
            var found = GetFakeUserIp(id);
            if (found == null)
            {
                var user = new User()
                {
                    Id = Guid.NewGuid(),
                    Account = accountName,
                    AccountId = id,
                    IsFakeIpUser = true,
                    Status = Status.Active,
                    FirstName = accountName,
                    LastName = "IP Login",
                    Sync_IsPlatformUser = true,
                    Email = string.Format("{0}.IPlogin@{0}.com", id)
                };
                _plainBlUser.CreateOrUpdate(user);
                found = user;
            }
            var clientUser = new ClientUser()
            {
                Id = found.Id,
                PasswordExpirationDate = DateTime.MaxValue,
                Password = AuthOperations.AuthOperations.DefaulHashedPasswordIpLogin()
            };
            _plainBlClientUser.CreateOrUpdate(clientUser);
            return found;
        }

        public bool DeleteFakeUserIpData(Guid userId)
        {
            var found = _plainBlClientUser.ReadAllWhere(a => a.Id == userId).FirstOrDefault();
            var foundUserData = _plainBlUser.ReadAllWhere(a => a.Id == userId).FirstOrDefault();
            if (foundUserData != null)
            {
                _plainBlUser.Delete(userId);
            }
            if (found != null)
            {
                _plainBlClientUser.Delete(userId);
            }
            return true;
        }
    }
}
